// lazy-loading.directive.ts
import { onMounted, onUnmounted } from 'vue';

interface LazyLoadOptions extends IntersectionObserverInit {
    rootMargin?: string;
    threshold?: number | number[];
}

export default {
    mounted(el: HTMLImageElement, binding: any) {
        let observer: IntersectionObserver;

        const loadImage = (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
            const [entry] = entries;
            if (entry.isIntersecting) {
                el.src = binding.value as string; // 将图片的真实 URL 赋值给 src
                observer.disconnect(); // 图片加载后取消观察
            }
        };

        observer = new IntersectionObserver(loadImage, {
            rootMargin: '0px',
            threshold: 1.0
        } as LazyLoadOptions);

        observer.observe(el); // 开始观察该元素

        // 在组件卸载时清理观察器
        onUnmounted(() => {
            observer.disconnect();
        });
    }
};